<?php
/* ************************************************************************
   Map Medley PHP/Server

   Copyright: 2011 Brant Anderson

   License: New BSD License

   Authors: Brant Anderson

************************************************************************ */
require_once "server/lib/JSON.phps";

/*
 * This is the mmserv class for use with mmclient.
 */

class class_mmserv extends ServiceIntrospection
{
    /**
     * testJson - For experimenting.
     *
     * @param params
     *   An array containing the parameters to this method
     *
     * @param error
     *   An object of class JsonRpcError.
     *
     * @return
     *   Success: Whatever I'm testing.
     *   Failure: null
     */
    function method_testJson($params, $error)
    {
        if (count($params) != 1)
        {
            $error->SetError(JsonRpcError_ParameterMismatch,
                             "Expected 1 parameter; got " . count($params));
            return $error;
        }
        $rgb = $this->hexToRGB($params[0]->hexcolor);
        
        return $rgb;
    }

    /**
     * isLoggedIn
     *
     * @param params
     *   An array containing the parameters to this method
     *
     * @param error
     *   An object of class JsonRpcError.
     *
     * @return
     *   Success: The username of the user logged in.
     *   Failure: An empty string.
     */
    function method_isLoggedIn($params, $error)
    {
        global $session;
        if (count($params) != 0)
        {
            $error->SetError(JsonRpcError_ParameterMismatch,
                             "Expected 0 parameters; got " . count($params));
            return $error;
        }
        
        if ($session->logged_in == true)
        {
          return $session->username;
        }
        else
        {
          return "";
        }
    }
    
    /**
     * login
     *
     * @param params
     *   An array containing the parameters to this method
     *
     * @param error
     *   An object of class JsonRpcError.
     *
     * @return
     *   Success: Returns true.
     *   Failure: Returns false.
     */
    function method_login($params, $error)
    {
        global $session, $database;
        if (count($params) != 1)
        {
            $error->SetError(JsonRpcError_ParameterMismatch,
                             "Expected 1 parameter; got " . count($params));
            return $error;
        }

      /* Username error checking */
      if(strlen(trim($params[0]->user)) == 0){
         return false;
      }
      else{
         /* Check if username is not alphanumeric */
         if(!preg_match("/^([0-9a-z])*$/i", trim($params[0]->user))){
            return false;
         }
      }

      /* Password error checking */
      if(!$params[0]->pass){
         return false;
      }

      /* Checks that username is in database and password is correct */
      $subuser = stripslashes($params[0]->user);
      $subpass = $params[0]->pass;
      $result = $database->confirmUserPass($subuser, md5($subpass));

      /* Check error codes */
      if($result == 1){
         return false;
      }
      else if($result == 2){
         return false;
      }

      /* Username and password correct, register session variables */
      $session->userinfo  = $database->getUserInfo($subuser);
      $session->username  = $_SESSION['username'] = $session->userinfo['username'];
      $session->userid    = $_SESSION['userid']   = $session->generateRandID();
      $session->userlevel = $session->userinfo['userlevel'];
      
      /* Insert userid into database and update active users table */
      $database->updateUserField($session->username, "userid", $session->userid);
      $database->addActiveUser($session->username, $session->time);
      $database->removeActiveGuest($_SERVER['REMOTE_ADDR']);

      /* Login completed successfully */
      return true;
    }

    /**
     * logout
     *
     * @param params
     *   An array containing the parameters to this method
     *
     * @param error
     *   An object of class JsonRpcError.
     *
     * @return
     *   Success: This will always succeed (as far as I know).
     *   Failure: null
     */
    function method_logout($params, $error)
    {
        global $session;
        if (count($params) != 0)
        {
            $error->SetError(JsonRpcError_ParameterMismatch,
                             "Expected 0 parameters; got " . count($params));
            return $error;
        }

        $session->logout();

        return true;
    }
        
    /**
     * getLayerExtent
     *
     * @param params
     *   An array containing the parameters to this method
     *
     * @param error
     *   An object of class JsonRpcError.
     *
     * @return
     *   Success: The extent min/max-x/y.
     *   Failure: null
     */
    function method_getLayerExtent($params, $error)
    {
        global $database;
        if (count($params) != 1)
        {
            $error->SetError(JsonRpcError_ParameterMismatch,
                             "Expected 1 parameter; got " . count($params));
            return $error;
        }

        $query = "SELECT xMin(the_geom) as minx, 
                  yMin(the_geom) as miny,
                  xMax(the_geom) as maxx, 
                  yMax(the_geom) as maxy FROM gis.".$params[0]->layername;

        $result = $database->query($query);
        if (!$result)
        {
            $error->SetError(JsonRpcError,
                             "Problem with query " . $query . ": " . pg_last_error(), 1000);
            return $error;
        }
       
        $flag = true;
        while($myrow = pg_fetch_array($result))
        {
            if ($flag == true)
            {
                $minx = $myrow['minx'];
                $miny = $myrow['miny'];
                $maxx = $myrow['maxx'];
                $maxy = $myrow['maxy'];
                $flag = false;
            }
            else
            {
                if ($minx > $myrow['minx'])
                {
                    $minx = $myrow['minx'];
                }
                if ($miny > $myrow['miny'])
                {
                    $miny = $myrow['miny'];
                }
                if ($maxx < $myrow['maxx'])
                {
                    $maxx = $myrow['maxx'];
                }
                if ($maxy < $myrow['maxy'])
                {
                    $maxy = $myrow['maxy'];
                }
            }
        } 

        $extent = Array();

        $extent["minx"] = $minx;
        $extent["miny"] = $miny;
        $extent["maxx"] = $maxx;
        $extent["maxy"] = $maxy;

        return $extent;
    }  
  
    /**
     * getMapImg
     *
     * @param params
     *   An array containing the parameters to this method
     *
     * @param error
     *   An object of class JsonRpcError.
     *
     * @return
     *   Success: The URL to the generated map image.
     *   Failure: null
     */
    function method_getMapImg($params, $error)
    {
        global $database;        
        if (count($params) != 1)
        {
            $error->SetError(JsonRpcError_ParameterMismatch,
                             "Expected 1 parameter; got " . count($params));
            return $error;
        }
        
        // Load some default settings
        $map_path="/var/www/sites/mapmedley/client/";
        $map = ms_newMapObj($map_path."config.map");

        // Dynamic Layers
        // Need to design a better database... This code is for testing.
        $qdl = "SELECT * FROM mmdoc_doc_layer WHERE doc_id=".$params[0]->doc_id; // ORDER BY sort
        $qdldata = $database->query($qdl);
        if (!$qdldata)
        {
            $error->SetError(JsonRpcError,
                             "Problem with query " . $qdl . ": " . pg_last_error(), 1000);
            return $error;
        }

        while($qdl_row = pg_fetch_array($qdldata))
        {
            $ql = "SELECT * FROM mmdoc_layer WHERE layer_id=".$qdl_row['layer_id'];
            $layerdata = $database->query($ql);
            if (!$layerdata)
            {
                $error->SetError(JsonRpcError,
                             "Problem with query " . $ql . ": " . pg_last_error(), 1000);
                return $error;
            }
        
            while($layer_row = pg_fetch_array($layerdata))
            {
              
              // LAYER DETAILS
              $layer = ms_newLayerObj($map);
              // NAME
              $layer->set("name", trim($layer_row['name']));
              
              // PROJECTION
              $layer->setProjection($layer_row['projection']);
              // CONNECTION
              $layer->setConnectionType(MS_POSTGIS);
              $layer->set("connection", "user=gis_master dbname=gistest host=localhost port=5432 password=gisisggs");
              $layer->set("data", "the_geom from gis.".$layer->name);
              
              // TYPE
              if (trim($layer_row['type']) == "polygon")
              {
                $layer->set("type", MS_LAYER_POLYGON);
              }
              
              // STATUS
              if (trim($layer_row['status']) == "on")
              {
                $layer->set("status", MS_ON);
              }
              else
              {
                $layer->set("status", MS_OFF);
              }
              
              // CLASS DETAILS
              $qlc = "SELECT * FROM mmdoc_layer_class WHERE layer_id=".$layer_row['layer_id']; // ORDER BY sort
              $qlcdata = $database->query($qlc);
              if (!$qlcdata)
              {
                  $error->SetError(JsonRpcError,
                                   "Problem with query " . $qlc . ": " . pg_last_error(), 1000);
                  return $error;
              }
              
              while ($qlc_row = pg_fetch_array($qlcdata))
              {
                $qc = "SELECT * FROM mmdoc_class WHERE class_id=".$qlc_row['class_id'];
                $classdata = $database->query($qc);
                if (!$classdata)
                {
                    $error->SetError(JsonRpcError,
                                     "Problem with query " . $qc . ": " . pg_last_error(), 1000);
                    return $error;
                }
                
                while($class_row = pg_fetch_array($classdata))
                {
                  $layer_class = ms_newClassObj($layer);
                  // NAME
                  $layer_class->set("name", $class_row['name']);
                  
                  // STYLE DETAILS
                  $qcs = "SELECT * FROM mmdoc_class_style WHERE class_id=".$class_row['class_id']; // ORDER BY sort
                  $qcsdata = $database->query($qcs);
                  if (!$qcsdata)
                  {
                      $error->SetError(JsonRpcError,
                                       "Problem with query " . $qcs . ": " . pg_last_error(), 1000);
                      return $error;
                  }

                  while ($qcs_row = pg_fetch_array($qcsdata))
                  {
                    
                    $qs = "SELECT * FROM mmdoc_style WHERE style_id=".$qcs_row['style_id'];
                    $styledata = $database->query($qs);
                    if (!$styledata)
                    {
                        $error->SetError(JsonRpcError,
                                         "Problem with query " . $qs . ": " . pg_last_error(), 1000);
                        return $error;
                    }
                    
                    while($style_row = pg_fetch_array($styledata))
                    {
                      $style = ms_newStyleObj($layer_class);
                      // COLOR
                      $color = $this->hexToRGB($style_row['color']);
                      $style->color->setRGB($color['r'], $color['g'], $color['b']);
                      // OUTLINE COLOR
                      $outlinecolor = $this->hexToRGB($style_row['outlinecolor']);
                      $style->outlinecolor->setRGB($outlinecolor['r'], $outlinecolor['g'], $outlinecolor['b']);
                    }

                  }

                }
                
              }
              
            }
            
        }

        /*
        $layer = ms_newLayerObj($map);
        $layer->set("name", "countries_simpl");
        $layer->set("type", MS_LAYER_POLYGON);
        $layer->set("status", MS_DEFAULT);
        $layer->setConnectionType(MS_POSTGIS);
        $layer->set("connection", "user=gis_master dbname=gistest host=localhost port=5432 password=gisisggs");
        $layer->set("data", "the_geom from gis.".$layer->name);
        $layer->setProjection("init=epsg:4326");

        $layer_class = ms_newClassObj($layer);
        $layer_class->set("name", "Countries");

        $style = ms_newStyleObj($layer_class);
        $style->color->setRGB(200, 200, 200);
        $style->outlinecolor->setRGB(100, 100, 100);
        */

        $map->setSize($params[0]->width, $params[0]->height);
        $map->setExtent($params[0]->minx, $params[0]->miny, $params[0]->maxx, $params[0]->maxy);

        $image=$map->draw();
        $image_url=$image->saveWebImage();           

        return $image_url;
    }
    
    // Helper functions
    static function hexToRGB($hex)
    {
      $red = hexdec(substr($hex, 0, 2));
      $green = hexdec(substr($hex, 2, 2));
      $blue = hexdec(substr($hex, 4, 2));
    
      $rgb = Array();
      $rgb['r'] = $red;
      $rgb['g'] = $green;
      $rgb['b'] = $blue;
      
      return $rgb;  
    }
}

?>
